package com.smcdd.cdb.dbo.cdb_dbo.service.presenter;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.network.HttpObserver;
import com.smcdd.cdb.dbo.cdb_dbo.network.factory.RetrofitFactory;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.BaseResponseEntity;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.MainTenance;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.PageMap;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.StoreInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.Tain;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.Tain_v2;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.ToDayCdbInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.IMaintain;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.MaintainActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.MaintainFiltrateActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.StatisticsActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.TainMapActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.adapter.TainAdapter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BasePresenter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DateUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DialogUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainEncry;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainVersion;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.TainDialog;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.TainYiDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 作者：Administrator on 2017/7/17 20:33
 * 邮箱：zhanghuaiha@gmail.com
 */

public class MaintainPresenter extends BasePresenter<IMaintain> {

    private String versionCode;
    private String id;
    private String udid;
    private RecyclerView rv;
    private TextView tv;
    private LinearLayoutManager linearLayoutManager;
    private TainAdapter tainAdapter;
    private int type = 0;
    private int num = 1;
    private int total;

    private String date = "";
    private String status = "";
    private TainDialog listDialog;
    private ImageView bg;
    private Dialog dialog;
    private List<Tain_v2> yet;
    private List<Tain_v2> not;
    private List<Tain_v2> yi;
    private String new_date;
    private List<Tain_v2> data;
    private List<PageMap> mList;
    private SwipeRefreshLayout sw;
    private boolean refreshing;
    private TainYiDialog yiDialog;
    private EditText search;

    public MaintainPresenter(BaseActivity context) {
        super(context);
    }

    public void loadContacts(){
        versionCode = ObtainVersion.getVersionName(mContext);
        id = App.SP.getString("id", "");
        udid = App.SP.getString("udid", "");
        rv = getView().getRv();
        tv = getView().getTV();
        bg = getView().getBg();
        sw = getView().getSw();
        search = getView().getSearch();
        linearLayoutManager = new LinearLayoutManager(mContext);
        rv.setLayoutManager(linearLayoutManager);
        setAdapter();
        //地图
        getView().getSort().setOnClickListener(v -> {
            if (data != null && data.size() > 0) {
                mList = new ArrayList<>();
                PageMap map = null;
                for (Tain_v2 tain_v2 : data) {
                    map = new PageMap();
                    map.setLatitude(tain_v2.getStore_info().getLatitude());
                    map.setLongitude(tain_v2.getStore_info().getLongitude());
                    map.setMaintained_status( tain_v2.getMaintained_status());
                    map.setStatus(tain_v2.getStatus());
                    map.setName(tain_v2.getStore_info().getName());
                    mList.add(map);
                }

                Intent intent  = new Intent(mContext,TainMapActivity.class);
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("list", (ArrayList<? extends Parcelable>) mList);// 序列化
                intent.putExtras(bundle);
                intent.putExtra("time",date);

                mContext.startActivity(intent);
            }else {
                ToastUtil.showToast("数据加载中，请稍后");
            }

        });
        //筛选
//        getView().getSort().setOnClickListener(v -> {
//            Intent intent  = new Intent(mContext,MaintainFiltrateActivity.class);
//            intent.putExtra("list", (Serializable) data);
//            intent.putExtra("status", status);
//            intent.putExtra("date", date);
//            intent.putExtra("flags", flags);
//            mContext.startActivity(intent);
//        });

        //下拉刷新
        sw.setColorSchemeResources(R.color.title_bg,R.color.blue);
        sw.setOnRefreshListener(() -> {
            refreshing = sw.isRefreshing();
            loadNetWork("0",date,"");
        });

    }

    private String typeCdb = "";

    private void setAdapter() {
        if (tainAdapter == null) {
            tainAdapter = new TainAdapter(mContext);
        }
        rv.setAdapter(tainAdapter);
        tainAdapter.setItemClickListenter((dataBean, position,flag,i) -> {
            long l = 0;
            if (i == 1) {
                if ("4".equals(dataBean.getStore_info().getStore_type())) {
                    typeCdb = "4";
                    if (status.equals("1")) {
                        loadDiaolog(date,dataBean.getMima_charging_info_ids());
                    }else{
                        if (this.date!= null&&!this.date.equals("")) {
                            long time_long = DateUtils.getTime_long(date);
                            l = time_long - 86400000;
                        }else {
                            l = System.currentTimeMillis() - 86400000;
                        }
                        String time = DateUtils.getTime(l);
                        loadDiaolog(time,dataBean.getMima_charging_info_ids());
                    }
                }else {
                    typeCdb = "1";
                    if (flag) {
                        if (status.equals("1")) {
                            loadDiaolog(date,dataBean.getCharging_info_ids());
                        }else{
                            if (this.date!= null&&!this.date.equals("")) {
                                long time_long = DateUtils.getTime_long(date);
                                l = time_long - 86400000;
                            }else {
                                l = System.currentTimeMillis() - 86400000;
                            }
                            String time = DateUtils.getTime(l);
                            loadDiaolog(time,dataBean.getCharging_info_ids());
                        }
                    }else {
                        //已维护
                        RecordDialog(date,dataBean.getWifi_already_maintained_ids());
                    }
                }
            }else {
                if (dataBean.getStore_info().getStore_type().equals("4")) {
                    typeCdb = "4";
                    loadDiaolog(date,dataBean.getMima_charging_info_ids());
                }else {
                    typeCdb = "1";
                    loadDiaolog(date,dataBean.getCharging_info_ids());
                }
            }
        });

        //条目点击事件
        tainAdapter.setItemsClickListenter((dataBean, position) -> {
            Intent intent = new Intent(mContext, StatisticsActivity.class);
            intent.putExtra("id",dataBean.getStore_info().getId());
            intent.putExtra("name",dataBean.getStore_info().getName());
            mContext.jumpToActivity(intent);
        });



    }

    public void setType(int type){
        num = 0;
        this.type = type;
        loadNetWork(num+"",date,status);
    }
    //维护成功数据
    public void yet(String type){
        status = type;
        tainAdapter.visibleIsgone(true);
        tainAdapter.visible2gone(true);
        tainAdapter.addData(yet);
    }

    //待维护数据
    public void not(String type){
        status = type;
        tainAdapter.visibleIsgone(false);
        tainAdapter.addData(not);
        tainAdapter.visible2gone(true);
    }
    //已维护数据
    public void yi(String type){
        tainAdapter.visibleIsgone(true);
        tainAdapter.visible2gone(false);
        tainAdapter.addData(yi);
        status = type;
    }

    public List<Tain_v2> getDate(){
        if (status.equals("0")) {
            return not;
        }else if (status.equals("2")) {
            return yi;
        }else if (status.equals("1")) {
            return yet;
        }
        return data;
    }
    private String name;
    public void searh(String tv,List<Tain_v2> list){
        List<Tain_v2> filterDateList = new ArrayList<>();
        if (tv.equals("取消")) {
            search.setText("");
            filterDateList = list;
        }else {
            String s = search.getText().toString().trim();
            if (TextUtils.isEmpty(s)) {
                filterDateList = list;
            }else {
                if (!list.contains(s)) {
                    filterDateList.clear();
                    for (Tain_v2 info : list) {
                        name = info.getStore_info().getName();
                        if (name.indexOf(s) != -1) {
                            int i = name.indexOf(s);
                            filterDateList.add(info);
                        }
                    }
                }
            }
        }

        tainAdapter.addData(filterDateList);
    }





    //加载默认数据
    public void loadNetWork(String num,String date,String status){
        getView().getYet().setSelected(false);
        getView().getNot().setSelected(false);
        getView().getYi().setSelected(false);
        getView().getYesterday().setSelected(true);
        getView().getTomorrow().setSelected(true);
        TSDialog();
        String time = System.currentTimeMillis() + "";
        this.date = date;
        this.status = status;
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",time);
        map.put("v",versionCode);
        map.put("i", NetWorkCodeInfo.MAINTENANCE_PAGE_V2);
        map.put("udid",udid);
        map.put("eid",id);
        map.put("page_size","1000");
        map.put("page_index","0");
        if (this.date!= null&&!this.date.equals("")) {
            map.put("date",this.date);
        }
        if (this.status!= null &&!this.status.equals("")) {
            map.put("status",this.status);
        }
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
//        ToastUtil.showToast(date);
        RetrofitFactory.getmInstanse().mApi.getTain_v2(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<List<Tain_v2>>>() {
                    @Override
                    public void success(BaseResponseEntity<List<Tain_v2>> listBaseResponseEntity) {
                        if (listBaseResponseEntity.code == 200) {
                            new_date = listBaseResponseEntity.new_date;
                            long l = DateUtils.S1compareS2(date, new_date, "yyyy-MM-dd");
                            if (l < 0) {
                                getView().getAc().flag = false;
                            }else {
                                getView().getTomorrow().setSelected(false);
                                getView().getAc().flag = true;
                            }

                            data = listBaseResponseEntity.data;
                            tainAdapter.addData(data);
                            if (data.size() == 0) {
                                bg.setVisibility(View.VISIBLE);
                                rv.setVisibility(View.INVISIBLE);
                            }else {
                                bg.setVisibility(View.INVISIBLE);
                                rv.setVisibility(View.VISIBLE);
                            }
                            if (yet == null) {
                                yet = new ArrayList<Tain_v2>();
                            }else{
                                yet.clear();
                            }
                            if (not == null) {
                                not = new ArrayList<Tain_v2>();
                            }else {
                                not.clear();
                            }
                            if (yi == null) {
                                yi = new ArrayList<Tain_v2>();
                            }else {
                                yi.clear();
                            }

                            for (Tain_v2 tain_v2 : data) {
                                if (tain_v2.getStatus().equals("1")) {
                                    //维护成功
                                    yet.add(tain_v2);
                                }else {
                                    //待维护
                                    not.add(tain_v2);
                                }
                                if (tain_v2.getMaintained_status() == 1) {
                                    yi.add(tain_v2);
                                    not.remove(tain_v2);
                                }
                            }
                            
                            getView().getYet().setText("待维护 "+not.size());
                            getView().getNot().setText("维护成功 "+yet.size());
                            getView().getYi().setText("已维护"+yi.size());
                            if (listBaseResponseEntity.is_calculation == 1) {
                                //计算成功
                                try {
                                    int d = (int) (yet.size() * 100.0 / yi.size());
                                    if (d > 100) {
                                        d = 100;
                                    }
                                    getView().getDbl().setText("维护成功率"+d+"%");
                                }catch (Exception e){
                                    getView().getDbl().setText("维护成功率"+0+"%");
                                }

                            }else {
                                getView().getDbl().setText("暂未统计");
                            }

                        }
                        if(refreshing) sw.setRefreshing(false);
                        dialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if(refreshing) sw.setRefreshing(false);
                        dialog.dismiss();
                        ToastUtil.showToast(mContext.getString(R.string.error_date));
                    }
                });
    }

    public String getTime(){
        return new_date;
    }


    /**
     * 获取dialog数据
     * @param date
     * @param charging_info_ids
     */
    public void loadDiaolog(String date,String charging_info_ids){
        dialog.show();
        String time = System.currentTimeMillis() + "";
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",time);
        map.put("v",versionCode);
        map.put("i", NetWorkCodeInfo.MAINTENANCE_CHARGING);
        map.put("udid",udid);
        map.put("eid",id);
        map.put("date",date);
        map.put("charging_info_ids",charging_info_ids);
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
        RetrofitFactory.getmInstanse().mApi.getmaintenance(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<List<MainTenance>>>() {
                    @Override
                    public void success(BaseResponseEntity<List<MainTenance>> mainTenanceBaseResponseEntity) {
                        if (mainTenanceBaseResponseEntity.code == 200) {
                            List<MainTenance> data = mainTenanceBaseResponseEntity.data;
                            Dialog(data);
                        }else {
                            DialogUtils.TSDialog(mContext,mainTenanceBaseResponseEntity.message,true);
                        }
                        dialog.dismiss();
                    }
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        dialog.dismiss();
                        ToastUtil.showToast(mContext.getString(R.string.error_date));
                    }
                });
    }

    public void RecordDialog(String date,String wifi_already_maintained_ids){
        String time = System.currentTimeMillis() + "";
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",time);
        map.put("v",versionCode);
        map.put("i", NetWorkCodeInfo.ALREADY_MAINTENANCE_CHARGING);
        map.put("udid",udid);
        map.put("eid",id);
        map.put("date",date);
        map.put("charging_info_ids",wifi_already_maintained_ids);
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
        RetrofitFactory.getmInstanse().mApi.getAlreadymaintenance(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<List<ToDayCdbInfo>>>() {
                    @Override
                    public void success(BaseResponseEntity<List<ToDayCdbInfo>> listBaseResponseEntity) {
                        if (listBaseResponseEntity.code == 200) {
                            dayDialog(listBaseResponseEntity.data);
                        }else {
                            DialogUtils.TSDialog(mContext,listBaseResponseEntity.message,true);
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        ToastUtil.showToast(mContext.getString(R.string.error_date));
                    }

                });
    }



    public void Dialog( List<MainTenance> data) {
        listDialog = new TainDialog(mContext,data,typeCdb);
        listDialog.show();
    }

    public void dayDialog( List<ToDayCdbInfo> data) {
        yiDialog = new TainYiDialog(mContext,data);
        yiDialog.show();
    }


    public void TSDialog(){
        dialog = DialogUtils.uploadDialog(mContext, mContext.getString(R.string.upload), true);
    }
    private boolean flags = true;
    private boolean isDay = true;

    public void visible2gone(boolean flag){
        flags = flag;
        tainAdapter.visible2gone(flag);
    }

    public void visibleIsgone(boolean flag){
        isDay = flag;
        tainAdapter.visibleIsgone(flag);
    }
}
